Loading packages

library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(stringr)
library(plotly)
## Warning: package 'plotly' was built under R version 3.4.4
## Loading required package: ggplot2
## Warning: package 'ggplot2' was built under R version 3.4.4
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout

Plotly

#name data file
dat <- read.csv('mobile-food-sf.csv', stringsAsFactors = FALSE)

#Plots with Plotly
day_freqs <- table(dat$DayOfWeekStr)

barplot(day_freqs, border = NA, las = 3)

plot_ly(x = names(day_freqs),
        y = day_freqs,
        type = 'bar')
#putting data in a tibble
# day frequencies table
day_counts <- dat %>% 
  select(DayOfWeekStr) %>%
  group_by(DayOfWeekStr) %>%
  summarise(count = n()) %>%
  arrange(desc(count))
day_counts
## # A tibble: 7 x 2
##   DayOfWeekStr count
##   <chr>        <int>
## 1 Friday        1105
## 2 Wednesday     1095
## 3 Thursday      1090
## 4 Tuesday       1081
## 5 Monday        1080
## 6 Saturday       533
## 7 Sunday         263
#passing day_counts to plot_ly
plot_ly(day_counts, 
        x = ~DayOfWeekStr, 
        y = ~count,
        type = 'bar')
#reordering the bars
plot_ly(day_counts, 
        x = ~reorder(DayOfWeekStr, count), 
        y = ~count,
        type = 'bar')

Times subsetting

#changing times using column starttime
# toy string
time1 <- '10AM'

#hour
str_sub(time1, start =1, end =2)
## [1] "10"
#period
str_sub(time1, start = 3, end = 4)
## [1] "AM"
#subset hour and periods with str_sub()
times <- c('12PM', '10AM', '9AM', '8AM', '2PM')

# subset time
str_sub(times, end = -3)
## [1] "12" "10" "9"  "8"  "2"
# subset period
str_sub(times, start = -2)
## [1] "PM" "AM" "AM" "AM" "PM"
#using function str_replace()
str_replace(times, pattern = 'AM|PM', replacement = '')
## [1] "12" "10" "9"  "8"  "2"
#Using times, create a numeric vector hours containing just the number time (i.e. hour)
hour <- str_sub(times, end = -3)
hours <- as.double(hour)
hours
## [1] 12 10  9  8  2
#Using times, create a character vector periods containing the period, e.g. AM or PM
periods <- str_sub(times, start = -2)
periods
## [1] "PM" "AM" "AM" "AM" "PM"
#Use plot_ly() to make a barchart of the counts for AM and PM values.
periodsdat <- as.data.frame(periods)

library(magrittr)

periods_table <- periodsdat %>%
  group_by(periods) %>%
  summarise(count = n())

periods_table
## # A tibble: 2 x 2
##   periods count
##   <fct>   <int>
## 1 AM          3
## 2 PM          2
plot_ly(periods_table, x = ~periods,
        y = ~count,
        type = 'bar')
#Write R code to create a vector start24 that contains the hour in 24hr scale.
converted_24 <- function(x) {
  time_counts <- rep(0, length(x))
  for (i in seq_along(x)) {
  if (x[i] == '12PM') {
    time_counts[i] <- (as.double(str_replace(x[i], pattern = 'AM|PM', replacement = '')))
  }
    
  else if ((str_sub(x[i], start = -2)) == 'PM') {
    time_counts[i] <- (as.double(str_replace(x[i], pattern = 'AM|PM', replacement = ''))) + 12
  }
  else if (x[i] == '12AM') {
    time_counts[i] <- (as.double(str_replace(x[i], pattern = 'AM|PM', replacement = ''))) -12
  }
  else {
    time_counts[i] <- (as.double(str_replace(x[i], pattern = 'AM|PM', replacement = '')))
      }
  }
  return(time_counts)
  }
converted_24(times)
## [1] 12 10  9  8 14
#With the starting and ending hours, calculate the duration, and add one more column duration to the data frame dat:
start <- converted_24(dat$starttime)
end <- converted_24(dat$endtime)
dat <- mutate(dat, duration = end-start)
head(dat)
##   DayOfWeekStr starttime endtime          PermitLocation
## 1       Friday      10AM    10PM         200 SHOTWELL ST
## 2       Friday       1PM     2PM       180 MONTGOMERY ST
## 3       Friday      10AM    11AM 101 EXECUTIVE PARK BLVD
## 4       Friday      10AM     3PM         290 TOWNSEND ST
## 5       Friday      10AM    11AM         299 ILLINOIS ST
## 6       Friday      10AM    11AM         1828 EGBERT AVE
##                                                                                                                                                                                                                                                                                                                                optionaltext
## 1                                                                                                                                                                                                                                                                       Tacos, Burritos, Tortas, Quesadillas, Mexican Drinks, Aguas Frescas
## 2                                                                                                                                                                                                                                                                                 Cold Truck: sandwiches, drinks, snacks, candy, hot coffee
## 3                                                                                                                                                                                                                                                                    Cold Truck: Pre-packaged Sandwiches, Various Beverages, Salads, Snacks
## 4                                                                                                                                                                                                                                             Hot Dogs, Hamburgers, Nachos, Steaks, Pastas, Asian Dishes, Tri-Tip Sandwiches, Sodas & Water
## 5                                                                                                                                                                                                                                                                         Cold Truck: Sandwiches, fruit, snacks, candy, hot and cold drinks
## 6 Cold Truck: Cheeseburgers, Burgers, Chicken Bake, Chili Dogs, Hot Dogs, Corn Dogs, Cup of Noodles, Egg Muffins, Tamales, Hot Sandwiches Quesadillas, Gatorade, Juice, Soda, Mikl, Coffee, Hot Cocoa, Hot Tea, Flan, Fruits, Fruit Salad, Yogurt, Candy, Chips,  Donuts, Cookies, Granola, Muffins & Various Drinks & Pre-Packaged Snacks.
##   ColdTruck         Applicant                             Location
## 1         N Santana ESG, Inc. (37.7651967350509,-122.416451692902)
## 2         Y Sun Rise Catering (37.7907890558203,-122.402273431333)
## 3         Y   Golden Catering (37.7111991003088,-122.394693339395)
## 4         N  Linda's Catering (37.7773000262759,-122.394812784799)
## 5         Y      May Catering                                 <NA>
## 6         Y     Bach Catering (37.7270392647114,-122.400141029645)
##   duration
## 1       12
## 2        1
## 3        1
## 4        5
## 5        1
## 6        1

Latitude and longitude

#Latitude and Longitude Coordinates
#definte vector with more location values to generalize code
locs <- dat$Location

#remove the parentheses
loc1 <- str_replace_all(locs, pattern = '\\(|\\)', replacement = '')
#remove the commas
lat_lon <- str_split(loc1, pattern = ',')
#use str_split() to create list lat_lon containing lat and longitude values
lat <- lapply(lat_lon, function(x) x[1])

#Create list of longitudes
lon <- lapply(lat_lon, function(x) x[2])

#convert both to vector
lat <- as.numeric(unlist(lat))
lon <- as.numeric(unlist(lon))

#add to data set
dat <- mutate(dat, lat = lat, lon = lon)
head(dat)
##   DayOfWeekStr starttime endtime          PermitLocation
## 1       Friday      10AM    10PM         200 SHOTWELL ST
## 2       Friday       1PM     2PM       180 MONTGOMERY ST
## 3       Friday      10AM    11AM 101 EXECUTIVE PARK BLVD
## 4       Friday      10AM     3PM         290 TOWNSEND ST
## 5       Friday      10AM    11AM         299 ILLINOIS ST
## 6       Friday      10AM    11AM         1828 EGBERT AVE
##                                                                                                                                                                                                                                                                                                                                optionaltext
## 1                                                                                                                                                                                                                                                                       Tacos, Burritos, Tortas, Quesadillas, Mexican Drinks, Aguas Frescas
## 2                                                                                                                                                                                                                                                                                 Cold Truck: sandwiches, drinks, snacks, candy, hot coffee
## 3                                                                                                                                                                                                                                                                    Cold Truck: Pre-packaged Sandwiches, Various Beverages, Salads, Snacks
## 4                                                                                                                                                                                                                                             Hot Dogs, Hamburgers, Nachos, Steaks, Pastas, Asian Dishes, Tri-Tip Sandwiches, Sodas & Water
## 5                                                                                                                                                                                                                                                                         Cold Truck: Sandwiches, fruit, snacks, candy, hot and cold drinks
## 6 Cold Truck: Cheeseburgers, Burgers, Chicken Bake, Chili Dogs, Hot Dogs, Corn Dogs, Cup of Noodles, Egg Muffins, Tamales, Hot Sandwiches Quesadillas, Gatorade, Juice, Soda, Mikl, Coffee, Hot Cocoa, Hot Tea, Flan, Fruits, Fruit Salad, Yogurt, Candy, Chips,  Donuts, Cookies, Granola, Muffins & Various Drinks & Pre-Packaged Snacks.
##   ColdTruck         Applicant                             Location
## 1         N Santana ESG, Inc. (37.7651967350509,-122.416451692902)
## 2         Y Sun Rise Catering (37.7907890558203,-122.402273431333)
## 3         Y   Golden Catering (37.7111991003088,-122.394693339395)
## 4         N  Linda's Catering (37.7773000262759,-122.394812784799)
## 5         Y      May Catering                                 <NA>
## 6         Y     Bach Catering (37.7270392647114,-122.400141029645)
##   duration      lat       lon
## 1       12 37.76520 -122.4165
## 2        1 37.79079 -122.4023
## 3        1 37.71120 -122.3947
## 4        5 37.77730 -122.3948
## 5        1       NA        NA
## 6        1 37.72704 -122.4001
#Plotting locations on a map
plot_ly(dat, x = ~lon, y = ~lat, type = 'scatter', mode = 'markers')
## Warning: Ignoring 40 observations
#RgoogleMaps
library(RgoogleMaps)
## Warning: package 'RgoogleMaps' was built under R version 3.4.4
# coordinates for center of the map
center <- c(mean(dat$lat, na.rm = TRUE), mean(dat$lon, na.rm = TRUE))

# zoom value
zoom <- min(MaxZoom(range(dat$lat, na.rm = TRUE), 
                    range(dat$lon, na.rm = TRUE)))

# san francisco map
map1 <- GetMap(center=center, zoom=zoom, destfile = "san-francisco.png")
PlotOnStaticMap(map1, dat$lat, dat$lon, col = '#ed4964', pch = 20)

Plotting locations

#Maps with 'ggmap'
library(ggmap)
## Error in library(ggmap): there is no package called 'ggmap'
# add variables 'lat' and 'lon' to the data frame
dat <- na.omit(dat)

# ggmap typically asks you for a zoom level, 
# but we can try using ggmap's make_bbox function:
sbbox <- make_bbox(lon = dat$lon, lat = dat$lat, f = .1)
## Error in make_bbox(lon = dat$lon, lat = dat$lat, f = 0.1): could not find function "make_bbox"
# get a 'terrain' map
sf_map <- get_map(location = sbbox, maptype = "terrain", source = "google")
## Error in get_map(location = sbbox, maptype = "terrain", source = "google"): could not find function "get_map"
#plot terrain map
ggmap(sf_map) + 
  geom_point(data = dat, 
             mapping = aes(x = lon, y = lat), 
             color = "red", alpha = 0.2, size = 1)
## Error in ggmap(sf_map): could not find function "ggmap"
#Look for specific types of food
foods <- dat$optionaltext[1:10]

#match burritos and Burritos
str_detect(foods, "Burritos")
##  [1]  TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
str_detect(foods, 'burritos')
##  [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
#try other pattern
str_detect(foods, 'tacos')
##  [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
str_detect(foods, 'quesadillas')
##  [1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
#create data frame burritos by subsetting
burritos <- subset(dat, optionaltext ='burritos')
head(burritos)
##   DayOfWeekStr starttime endtime          PermitLocation
## 1       Friday      10AM    10PM         200 SHOTWELL ST
## 2       Friday       1PM     2PM       180 MONTGOMERY ST
## 3       Friday      10AM    11AM 101 EXECUTIVE PARK BLVD
## 4       Friday      10AM     3PM         290 TOWNSEND ST
## 6       Friday      10AM    11AM         1828 EGBERT AVE
## 7       Friday      10AM    11AM           560 NATOMA ST
##                                                                                                                                                                                                                                                                                                                                optionaltext
## 1                                                                                                                                                                                                                                                                       Tacos, Burritos, Tortas, Quesadillas, Mexican Drinks, Aguas Frescas
## 2                                                                                                                                                                                                                                                                                 Cold Truck: sandwiches, drinks, snacks, candy, hot coffee
## 3                                                                                                                                                                                                                                                                    Cold Truck: Pre-packaged Sandwiches, Various Beverages, Salads, Snacks
## 4                                                                                                                                                                                                                                             Hot Dogs, Hamburgers, Nachos, Steaks, Pastas, Asian Dishes, Tri-Tip Sandwiches, Sodas & Water
## 6 Cold Truck: Cheeseburgers, Burgers, Chicken Bake, Chili Dogs, Hot Dogs, Corn Dogs, Cup of Noodles, Egg Muffins, Tamales, Hot Sandwiches Quesadillas, Gatorade, Juice, Soda, Mikl, Coffee, Hot Cocoa, Hot Tea, Flan, Fruits, Fruit Salad, Yogurt, Candy, Chips,  Donuts, Cookies, Granola, Muffins & Various Drinks & Pre-Packaged Snacks.
## 7                                                                                                                                                                                                                                                                                 Cold Truck: sandwiches, drinks, snacks, candy, hot coffee
##   ColdTruck         Applicant                             Location
## 1         N Santana ESG, Inc. (37.7651967350509,-122.416451692902)
## 2         Y Sun Rise Catering (37.7907890558203,-122.402273431333)
## 3         Y   Golden Catering (37.7111991003088,-122.394693339395)
## 4         N  Linda's Catering (37.7773000262759,-122.394812784799)
## 6         Y     Bach Catering (37.7270392647114,-122.400141029645)
## 7         Y Sun Rise Catering (37.7791347875605,-122.409112429172)
##   duration      lat       lon
## 1       12 37.76520 -122.4165
## 2        1 37.79079 -122.4023
## 3        1 37.71120 -122.3947
## 4        5 37.77730 -122.3948
## 6        1 37.72704 -122.4001
## 7        1 37.77913 -122.4091
#use lat and ln to display map of locations with burritos
ggmap(sf_map) + 
  geom_point(data = burritos, 
             mapping = aes(x = lon, y = lat), 
             color = "red", alpha = 0.2, size = 1)
## Error in ggmap(sf_map): could not find function "ggmap"